package com.example.himalaya;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.himalaya.adapters.AlbumListRvAdapter;
import com.example.himalaya.adapters.SuggestWordListRvAdapter;
import com.example.himalaya.base.BaseApplication;
import com.example.himalaya.interfaces.ISearchPresenter;
import com.example.himalaya.interfaces.ISearchViewCallback;
import com.example.himalaya.presenters.AlbumDetailPresenter;
import com.example.himalaya.presenters.SearchPresenter;
import com.example.himalaya.views.FlowTextLayout;
import com.example.himalaya.views.UILoader;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.word.HotWord;
import com.ximalaya.ting.android.opensdk.model.word.QueryResult;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SearchActivity extends AppCompatActivity implements ISearchViewCallback {

    private static final String TAG = "SearchActivity";

    private ImageView mBackBtn;
    private EditText mSearchInput;
    private TextView mSearchBtn;
    private FrameLayout mSearchContainer;
    private ISearchPresenter mSearchPresenter;
    private UILoader mUILoader;
    private FlowTextLayout mFlowTextLayout;
    private RecyclerView mSearchListRv;
    private AlbumListRvAdapter mAlbumListRvAdapter;
    private InputMethodManager mInputManager;
    private ImageView mSearchInputDeleteBtn;
    private RecyclerView mSuggestWordListRv;
    private SuggestWordListRvAdapter mSuggestWordListRvAdapter;

    private boolean mNeedSuggestWord = true;
    private TwinklingRefreshLayout mSearchListRefreshLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        mInputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        initView();
        initEvent();
        initPresenter();
    }

    private void initView() {
        mBackBtn = findViewById(R.id.iv_back);
        mSearchInput = findViewById(R.id.search_input);
        mSearchInput.postDelayed(new Runnable() {
            @Override
            public void run() {
                mSearchInput.requestFocus();
                mInputManager.showSoftInput(mSearchInput, InputMethodManager.SHOW_IMPLICIT);
            }
        }, 500);
        mSearchInput.setSelection(mSearchInput.getText().length());
        mSearchBtn = findViewById(R.id.search_search_btn);
        mSearchContainer = findViewById(R.id.search_container);
        mUILoader = new UILoader(this) {
            @Override
            protected View getSuccessView(ViewGroup container) {
                return createSuccessView(container);
            }
        };

        if (mUILoader.getParent() instanceof ViewGroup) {
            ((ViewGroup) mUILoader.getParent()).removeView(mUILoader);
        }
        mSearchContainer.addView(mUILoader);

        mSearchInputDeleteBtn = findViewById(R.id.search_input_delete);
        mSearchInputDeleteBtn.setVisibility(View.GONE);

    }

    private View createSuccessView(ViewGroup container) {
        View successView = LayoutInflater.from(this).inflate(R.layout.item_activity_search, container, false);
        //热词
        mFlowTextLayout = successView.findViewById(R.id.flow_text_layout);
        //搜索列表
        mSearchListRv = successView.findViewById(R.id.search_list_RV);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mSearchListRv.setLayoutManager(linearLayoutManager);
        mAlbumListRvAdapter = new AlbumListRvAdapter();
        mSearchListRv.setAdapter(mAlbumListRvAdapter);
        mSearchListRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.top = UIUtil.dip2px(view.getContext(),2);
                outRect.bottom = UIUtil.dip2px(view.getContext(), 2);
                outRect.left=UIUtil.dip2px(view.getContext(),5);
                outRect.right=UIUtil.dip2px(view.getContext(),5);
            }
        });

        //建议词
        mSuggestWordListRv = successView.findViewById(R.id.suggest_word_Rv);
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(this);
        mSuggestWordListRv.setLayoutManager(linearLayoutManager1);
        mSuggestWordListRvAdapter = new SuggestWordListRvAdapter();
        mSuggestWordListRv.setAdapter(mSuggestWordListRvAdapter);
        mSuggestWordListRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.top = UIUtil.dip2px(view.getContext(),2);
                outRect.bottom = UIUtil.dip2px(view.getContext(), 2);
                outRect.left=UIUtil.dip2px(view.getContext(),5);
                outRect.right=UIUtil.dip2px(view.getContext(),5);
            }
        });

        mSearchListRefreshLayout = successView.findViewById(R.id.search_list_refresh_layout);
        return successView;
    }

    private void initEvent() {
        mBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mSearchInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    if (mSearchPresenter != null) {
                        mSearchPresenter.getHotWord();
                        mSearchInputDeleteBtn.setVisibility(View.GONE);
                    }
                }else {
                    mSearchInputDeleteBtn.setVisibility(View.VISIBLE);
                    if (mSearchPresenter != null) {
                        if (mNeedSuggestWord) {
                            //触发联想查询
                            mSearchPresenter.getSuggestWord(s.toString());
                        }else {
                            mNeedSuggestWord = true;
                        }
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String keyword = mSearchInput.getText().toString().trim();
                if (TextUtils.isEmpty(keyword)) {
                    Toast.makeText(SearchActivity.this,"关键字不能为空",Toast.LENGTH_SHORT).show();
                }else {
                    if (mSearchPresenter != null) {
                        mSearchPresenter.doSearch(keyword);
                    }
                }

            }
        });
        mUILoader.setOnRetryClickListener(new UILoader.OnRetryClickListener() {
            @Override
            public void onRetryClick() {
                if (mSearchPresenter != null) {
                    mSearchPresenter.reSearch();
                }
            }
        });

        mFlowTextLayout.setClickListener(new FlowTextLayout.ItemClickListener() {
            @Override
            public void onItemClick(String text) {
                if (mSearchPresenter != null) {
                    mNeedSuggestWord = false;
                    mSearchInput.setText(text);
                    mSearchInput.setSelection(text.length());
                    mSearchPresenter.doSearch(text);
                }
            }
        });

        mSearchInputDeleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSearchInput != null) {
                    mSearchInput.setText("");
                }
            }
        });

        mSuggestWordListRvAdapter.setOnItemClickListener(new SuggestWordListRvAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String keyword) {
                if (mSearchPresenter != null) {
                    mNeedSuggestWord = false;
                    mSearchInput.setText(keyword);
                    mSearchInput.setSelection(keyword.length());
                    mSearchPresenter.doSearch(keyword);
                }
            }
        });

        mSearchListRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {

            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                BaseApplication.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(SearchActivity.this, "刷新成功...", Toast.LENGTH_SHORT).show();
                        mSearchListRefreshLayout.finishRefreshing();
                    }
                }, 500);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                    if (mSearchPresenter != null) {
                        mSearchPresenter.loadMore();
                    }

            }
        });

        mAlbumListRvAdapter.setOnItemClickListener(new AlbumListRvAdapter.onItemClickListener() {
            @Override
            public void OnItemClick(int position, Album album) {
                AlbumDetailPresenter albumDetailPresenter = AlbumDetailPresenter.getAlbumDetailPresenter();
                albumDetailPresenter.setTargetAlbum(album);

                //跳转到专辑详情界面
                Intent intent = new Intent(SearchActivity.this, DetailActivity.class);
                startActivity(intent);
            }
        });
    }

    private void initPresenter() {

        mSearchPresenter = SearchPresenter.getSearchPresenter();
        mSearchPresenter.registerViewCallBack(this);
        mSearchPresenter.getHotWord();
    }

    /**
     * 解决页面冲突
     */
    private void hideSuccessView(){
        mSuggestWordListRv.setVisibility(View.GONE);
        mFlowTextLayout.setVisibility(View.GONE);
        mSearchListRv.setVisibility(View.GONE);
    }


    @Override
    public void onSearchResultLoad(List<Album> albumList) {
        if (albumList != null) {
            mAlbumListRvAdapter.setData(albumList);
            hideSuccessView();
            mSearchListRv.setVisibility(View.VISIBLE);
            mUILoader.updateUIStatus(UILoader.UIStatus.SUCCESS);
        }
    }

    @Override
    public void onLoadMoreResultLoad(List<Album> albumList, boolean isOkay) {
        if (mSearchListRefreshLayout != null) {
            mSearchListRefreshLayout.finishLoadmore();
        }

        if (isOkay) {
            if (albumList != null) {
                mAlbumListRvAdapter.setData(albumList);
            }
        } else {
            Toast.makeText(this, "没有更多的内容", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onHotWordLoad(List<HotWord> hotWordList) {
        mInputManager.showSoftInput(mSearchInput, InputMethodManager.SHOW_IMPLICIT);
        List<String> hotWordsString = new ArrayList<>();
        hotWordsString.clear();
        for (HotWord hotWord : hotWordList) {
            String searchWord = hotWord.getSearchword();
            hotWordsString.add(searchWord);
        }
        if (mFlowTextLayout != null) {
            Collections.sort(hotWordsString);
            mFlowTextLayout.setTextContents(hotWordsString);
            hideSuccessView();
            mFlowTextLayout.setVisibility(View.VISIBLE);
            mUILoader.updateUIStatus(UILoader.UIStatus.SUCCESS);
        }

    }

    @Override
    public void onSuggestWordLoad(List<QueryResult> suggestWordsList) {
        hideSuccessView();
        mSuggestWordListRv.setVisibility(View.VISIBLE);
        mSuggestWordListRvAdapter.setData(suggestWordsList);
        mUILoader.updateUIStatus(UILoader.UIStatus.SUCCESS);
    }

    @Override
    public void onLoadLoading() {
        //隐藏键盘
        mInputManager.hideSoftInputFromWindow(mSearchInput.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
        mUILoader.updateUIStatus(UILoader.UIStatus.LOADING);
    }

    @Override
    public void onLoadNetworkError() {
        mUILoader.updateUIStatus(UILoader.UIStatus.NETWORK_ERROR);
    }

    @Override
    public void onLoadDataEmpty() {
        mUILoader.updateUIStatus(UILoader.UIStatus.EMPTY);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSearchPresenter != null) {
            mSearchPresenter.unRegisterViewCallBack(this);
            mSearchPresenter = null;
        }
    }
}